<?php

namespace app\admin\controller\qingdong\work;

use addons\qingdong\model\File;
use addons\qingdong\model\Flow;
use addons\qingdong\model\Message;
use addons\qingdong\model\OperationLog;
use app\admin\controller\qingdong\Base;
use addons\qingdong\model\Form;
use addons\qingdong\model\FormApproval;
use addons\qingdong\model\Approval as ApprovalModel;
use addons\qingdong\model\Staff;
use addons\qingdong\model\ExamineRecord;
use think\DB;
use fast\Tree;
use think\Exception;

/**
 * 审批列表
 */
class Approval extends Base {
    public function _initialize() {
        parent::_initialize();
        $this->model = new ApprovalModel();
        $form =FormApproval::where([])->select();
        $this->assign('form', $form);
    }

    /**
     * 审批列表
     */
    public function index() {
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list   = $this->model->with(['formapproval','createStaff'])->where($where)->where('create_staff_id', 'in', Staff::getMyStaffIds())->order($sort, $order)->paginate($limit);
            $row    = $list->items();
            $result = array("total" => $list->total(), "rows" => $row);

            return json($result);
        }

        return $this->view->fetch();
    }

    /**
     * 添加审批
     */
    public function add() {
        if ($this->request->isAjax()) {
            $data = $this->request->post('row/a');

            Db::startTrans();
            try {
                $formapprovals = FormApproval::where(array('id' => $data['formapproval_id']))->find();
                $types = Form::where(array('id' => $formapprovals['form_id']))->value('type');
                $data = Form::updateFormParams($types, $data);
                $data['data'] = $data;
                $result = ApprovalModel::createApproval($data);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            $this->success('提交成功');
        }
        $formId=input('id','');
        if(!$formId){
            $this->error('联系管理员');
        }
        $flow= Flow::getsteplist(Flow::APPROVAL_STATUS.'_'.$formId);
        if (empty($flow)) {
            $this->error('无可用审批流，请联系管理员');
        }
        $this->assign('flow',$flow);

        $formapproval = FormApproval::where(array('id'=>$formId))->find();
        $type = Form::where(array('id'=>$formapproval['form_id']))->value('type');
        $this->assign('form_data', Form::getDataValue($type));
        $this->assign('row', $formapproval);
        $this->assign('staff', Staff::where([])->column('name', 'id'));
        return $this->view->fetch();
    }


    /**
     * 审批详情
     */
    public function detail($ids = null) {
        $row = $this->model->where([
            'id'       => $ids
        ])->with(['createStaff'])->find();
        $row=$row->toArray();
        $row=array_merge($row,$row['content']);
        $formapproval = FormApproval::where(array('id'=>$row['formapproval_id']))->find();
        $type = Form::where(array('id'=>$formapproval['form_id']))->value('type');

        $form = Form::getDataValue($type,$row);
        foreach($form as $k=>$v){
            if($v['component'] == 'uploadImage' || $v['component'] == 'uploadFile'){
                if(key_exists($v['id'],$row)){
                    if(isset($row[$v['id']]) && $row[$v['id']]){
                        $whereT['id'] = array('in',$row[$v['id']]);
                        $fileinfo = File::where($whereT)->field('id,name,file_path')->select();
                        if($fileinfo){
                            $row[$v['id']] = $fileinfo;
                        }
                    }
                }
            }elseif($v['component'] == 'select'){
                if(isset($v['config']['multiple']) &&  $v['config']['multiple'] == true){
                    if(key_exists($v['id'],$row)){
                        if(is_array($row[$v['id']]) && $row[$v['id']]){
                            $row[$v['id']] = implode(',',$row[$v['id']]);
                        }
                    }
                }
            }
        }

        //审批人
        $where['id'] = array('in',$row['check_staff_ids']);
        $staff = Staff::where($where)->column('name');
        $row['staff_id'] = '';
        if($staff){
            $row['staff_id'] = implode(',',$staff);
        }
        $row['name'] = $formapproval['name'];


        $this->assign('examine_record',ExamineRecord::getList(ExamineRecord::APPROVAL_TYPE,$ids));

        $this->assign('flow',Flow::getstepdetail(Flow::APPROVAL_STATUS, $ids));

        $this->assign('form_data', $form);
        $this->assign('row', $row);
        return $this->view->fetch();
    }

    /**
     * 获取审批人列表
     */
    public function getstaff(){
        $pageSize = input('pageSize');
        $pageNumber = input('pageNumber');
        $where = [];
        if ($keyValue = $this->request->request("keyValue")) {
            $where['id'] = ['in',$keyValue];
        }
        $name       = input('name');
        if(!empty($name)){
            $where['name'] = ['like','%'.$name.'%'];
        }
        $staff = Staff::where($where)->where(['id'=>['neq',$this->_staff->id]])->field('id,name')->order('id desc')->paginate($pageSize, false, ['page' => $pageNumber]);
        return json(['list' => $staff->items(), 'total' => $staff->total()]);
    }

    /**
     * 删除审批
     */
    public function del($ids = null) {
        if ($this->request->isAjax()) {
            $map['id'] = array('in', $ids);
            $result    = $this->model->destroy($map);
            if (!$result) {
                $this->error('删除失败');
            }
            $this->success('删除成功');
        }

        return $this->view->fetch();
    }
}